/**
 * Created by shudong.msd(风骐) on 2016/4/27.
 */

'use strict';

app.factory('indexDataListService',['$http','$q','$timeout','$state',function($http,$q,$timeout,$state){

    var comutil = new commUtils();

    var service = {};

    var dataPromise = function(){
        var deferred = $q.defer();

        $http.get(UrlMappings.TOP20SEARCH,{
            params : {
                'access_token':comutil.getTocken()
            },
            headers: {
                'Accept':'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function (data) {
            deferred.resolve(data)
        }).error(function(data,status) {
            if(status=='401')comutil.logout($state);
            deferred.reject(data);
        });
        return deferred.promise;
    };


    // 初始化数据
    dataPromise().then(function(data){
        cacheData = data;
    });

    var cacheData = null;

    service.fetchData = function(scope,type){

        function timeFresh(){
            $timeout(function () {
                if(cacheData!=null){
                    initData(scope,type,cacheData);
                    return;
                }else{
                    timeFresh();
                }
            },100);
        }

        timeFresh();

        /*dataPromise().then(function(data){
            cacheData = data;

            initData(scope,type,data);

            if(!scope.$$phase) {
                scope.$apply();
            }
        });
*/
    };

    var initData = function (scope,type,data) {
        scope.leftRecordList = new Array(0);
        scope.rightRecordList = new Array(0);
        var tvObj = data[type];
        if(tvObj==null)return;
        scope.norm = tvObj['superNorm'];
        var timeStr = "第"+tvObj['index']+"周  (";
        timeStr += (tvObj['startTime']+"").substring(0,4)+'年 ';
        timeStr += (tvObj['startTime']+"").substring(4,6)+'月';
        timeStr += (tvObj['startTime']+"").substring(6,8)+'日-';
        timeStr += (tvObj['endTime']+"").substring(4,6)+'月';
        timeStr += (tvObj['endTime']+"").substring(6,8)+'日）';

        scope.timedetail = timeStr;

        for (var i in tvObj['datas']){
            var tmpObj = tvObj['datas'][i];
            if (tmpObj.order <= 10) {
                scope.leftRecordList.push({'ranknum':tmpObj.order,'name':tmpObj.name,'region':tmpObj.area,'im':tmpObj.norm});
            } else if(tmpObj.order <= 20)
            {
                scope.rightRecordList.push({'ranknum':tmpObj.order,'name':tmpObj.name,'region':tmpObj.area,'im':tmpObj.norm});
            }
            if (scope.leftRecordList.length + scope.rightRecordList.length >= 20)break;
        }
    };

    return service;

}]);